<template>
  <div class="purchase-apply-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span class="form-title">采购单</span>
          <div class="header-actions">>
            <el-button>商品记录</el-button>
            <el-button type="primary" @click="handleSubmit" :disabled="!selectedSupplier.SupplierName">{{
              isEdit ? '保存修改' : '保存并新增' }}</el-button>
            <el-button type="primary" @click="handleSubmit2" :disabled="!selectedSupplier.SupplierName">保存</el-button>
            <el-button>批量导入</el-button>
            <el-button @click="audit">审核</el-button>
            <el-button @click="chooseOrder">选择源单</el-button>
          </div>
        </div>
      </template>
      <div class="form-content">
        <el-form :model="form" label-width="100px" class="fixed-height-dialog" width="60%">
          <!-- 供应商信息头部 -->
          <div class="supplier-header">
            <div class="supplier-info-row">
              <div class="info-item">
                <span class="label">供应商:</span>
                <el-input v-model="selectedSupplier.SupplierName" placeholder="选择供应商(必选)" clearable disabled
                  style="width: 200px; margin-right: 20px;">
                  <template #append>
                    <el-button :icon="Search" @click="supplierDialog.open()" />
                  </template>
                </el-input>
                <span class="label">业务员:</span>
                <el-input v-model="form.created_by" placeholder="业务员" clearable style="width: 120px;margin-right: 20px;"
                  disabled>
                </el-input>
                <span class="label">单据日期:</span>
                <el-date-picker v-model="form.procurement_date" type="date" placeholder="选择单据日期"
                  style="width: 140px;" />
              </div>

            </div>
            <div class="supplier-detail-row">
              <div class="info-item">
                <span class="label">供应商发货地址:</span>
                <el-input v-model="form.procurement_address" placeholder="供应商发货地址" clearable style="width: 300px;" />
              </div>
            </div>
          </div>

          <!-- 采购物品明细 -->
          <div class="form-section">
            <div class="section-header">
              <div class="section-title">
                采购订单明细
                <el-button type="primary" link @click="openGoodsDialog" style="margin-left: 10px;">
                  <el-icon>
                    <Plus />
                  </el-icon>添加物品
                </el-button>
                <span class="item-count" v-if="form.detailList.length > 0">
                  共 {{ form.detailList.length }} 个物品
                </span>
              </div>
            </div>

            <el-table :data="form.detailList" border style="width: 100%" class="items-table" empty-text="暂无物品，请点击添加物品"
              :summary-method="getSummary" show-summary>
              <el-table-column label="序号" type="index" width="60" align="center" />
              <el-table-column label="商品编号" prop="goods_code" width="120" align="center" />
              <el-table-column label="物品名称" prop="goods_name" min-width="220" align="center" />
              <el-table-column label="规格型号" prop="goods_specifiction  " min-width="120" align="center" />
              <el-table-column label="品牌" prop="goods_brand" width="100" align="center" />
              <el-table-column label="单位" prop="goods_moreUint" width="120" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.goods_moreUint" style="width: 95%" :disabled="!scope.row.goods_moreUint"
                    @change="calculateDetailPrice(scope.row)">
                    <template v-if="scope.row.unitList">
                      <el-option v-for="item in scope.row.unitList" :key="item.id" :label="item.name"
                        :value="item.name" />
                    </template>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="仓库" prop="goods_store" width="180" align="center">
                <template #default="{ row, $index }">
                  <el-input :value="row.goods_store" readonly placeholder="选择仓库"
                    @click="openWarehouseDialog(row, $index)" style="width: 140px" />
                </template>
              </el-table-column>
              <el-table-column label="可用库存" prop="moreUnit_num" width="100" align="center" />
              <el-table-column label="数量" prop="procurementDetail_num" width="120" align="center">
                <template #default="{ row }">
                  <el-input-number v-model="row.procurementDetail_num" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" :min="1" :max="99999" :controls="false" placeholder="数量" />
                </template>
              </el-table-column>
              <el-table-column label="基本单位" prop="goods_unit" width="120" align="center" />
              <el-table-column label="基本数量" prop="unit_num" width="120" align="center" />
              <el-table-column label="检测数量" prop="inspected_quantity" width="160" align="center" />
              <el-table-column label="购货单价" prop="goods_price" width="120" align="center">
                <template #default="{ row }">
                  <el-input-number v-model="row.goods_price" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" :precision="2" :controls="false" :min="0" placeholder="0.00" />
                </template>
              </el-table-column>
              <el-table-column label="赠品" prop="gift" width="80" align="center">
                <template #default="{ row }">
                  <el-checkbox v-model="row.gift" label="赠品" :true-label="true" :false-label="false"
                    @change="calculateDetailPrice(row)" />
                </template>
              </el-table-column>
              <el-table-column label="含税单价" prop="afterDiscount_price" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.afterDiscount_price" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" disabled
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                </template>
              </el-table-column>
              <el-table-column label="折后含税单价" prop="afterDiscount_taxPrice" width="160" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.afterDiscount_taxPrice" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" disabled
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                </template>
              </el-table-column>
              <el-table-column label="折扣率(%)" prop="discount" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.discount" style="width: 80px" size="small" @change="calculateDetailPrice(row)"
                    oninput="value=value.replace(/[^\d]/g,'')" />
                </template>
              </el-table-column>
              <el-table-column label="折扣额" prop="discount_amount" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.discount_amount" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" disabled
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                </template>
              </el-table-column>
              <el-table-column label="折后单价" prop="discount_price" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.discount_price" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" disabled
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                </template>
              </el-table-column>
              <el-table-column label="金额" prop="amount" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.amount" style="width: 80px" size="small" @change="calculateDetailPrice(row)"
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')"
                    disabled />
                </template>
              </el-table-column>
              <el-table-column label="税率(%)" prop="tax" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.tax" style="width: 80px" size="small" @change="calculateDetailPrice(row)"
                    oninput="value=value.replace(/[^\d]/g,'')" />
                </template>
              </el-table-column>
              <el-table-column label="税额" prop="tax_amount" width="120" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.tax_amount" style="width: 80px" size="small"
                    @change="calculateDetailPrice(row)" disabled
                    oninput="value=value.replace(/[^\d.]/g,'').replace(/(\..*)\./g, '$1').replace(/\.(\d{2})\d+/, '.$1')" />
                </template>
              </el-table-column>
              <el-table-column label="价税合计" prop="totalAmount_includingTax" width="120" align="center">
                <template #default="{ row }">
                  ¥{{ row.totalAmount_includingTax?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column label="关联购货订单号" prop="procurementDetailOrder_code" width="120" align="center" />
              <el-table-column label="备注" prop="procurementDetail_remark" width="200" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.procurementDetail_remark" style="width: 160px" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center" fixed="right">
                <template #default="{ $index }">
                  <el-button type="danger" link @click="removeItem($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 其他信息 -->
          <div class="supplier-detail-row" style="margin-bottom: 20px;">
            <el-input v-model="form.procurement_remark" placeholder="暂无备注信息" type="textarea" />
          </div>
          <div class="supplier-detail-row" style="margin-bottom: 12px;">
            <span class="label">本次付款:</span>
            <el-input-number v-model="form.pay_amount" style="width: 100px;" :min="0.00" :max="9999999.99"
              :precision="2" :step="0.01" :controls="false" placeholder="0.00" />
            <span class="label">结算账户:</span>
            <el-select v-model="form.payment_account" placeholder="请选择结算账户" clearable style="width: 200px;"
              @change="handleAccountChange" >
              <el-option v-for="item in accountList" :key="item.account_id" :value="item.account_id"
                :label="item.account_name">
              </el-option>
            </el-select>
            <span class="label">采购费用:</span>
            <el-input v-model="form.procurement_amount" clearable style="width: 100px; " disabled />
            <span class="label">本次欠款:</span>
            <el-input :value="remainingAmount" clearable style="width: 100px; " disabled />
            <span class="label">交货方式:</span>
            <el-select v-model="form.delivery_method" placeholder="" clearable style="width: 120px;">
              <el-option value="快递物流">快递物流</el-option>
              <el-option value="自配送">自配送</el-option>
              <el-option value="自提">自提</el-option>
              <el-option value="其他">其他</el-option>
            </el-select>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 商品搜索列表弹出对话框 -->
    <el-dialog v-model="openGoodsDialogView" title="商品搜索列表" width="40%" style="height: auto; width: 800px;" draggable
      :show-close="true">
      <!-- 调用商品的搜索组件 -->
      <FreeGoodsSelect v-model="openGoodsDialogView" @update:visible="openGoodsDialogView = $event"
        @confirm="handleGoodsConfirm">
      </FreeGoodsSelect>
      <br /><br />
    </el-dialog>

    <!-- 供应商对话框 -->
    <SupplierDialog ref="supplierDialog" :supplier-list="SupplierList" @confirm="handleSupplierConfirm" />
  </div>


  <!-- 源单选择对话框 -->
  <el-dialog v-model="openComparisonGoodsDialogView" title="选择商品" width="70%">
    <div class="supplier-dialog-c   ontent">
      <!-- 搜索区域 - 按照图片样式重构 -->
      <div class="search-area">
        <div class="search-row">
          <div class="search-item">
            <span class="search-label">单据日期</span>
            <el-date-picker v-model="tempDateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" style="width: 240px;" @change="handleDateRangeChange" />
          </div>
          <div class="search-item">
            <span class="search-label">单据编号</span>
            <el-input v-model="searchForm.procurementOrder_code" placeholder="请输入" clearable style="width: 150px;" />
          </div>
          <div class="search-item">
            <span class="search-label">仓库</span>
            <el-select v-model="searchForm.goods_store" placeholder="请选择" clearable style="width: 120px;">
              <el-option label="仓库1" value="1" />
              <el-option label="仓库2" value="2" />
              <el-option label="仓库3" value="3" />
            </el-select>
          </div>
        </div>

        <div class="search-row">
          <div class="search-item">
            <span class="search-label">交货日期</span>
            <el-date-picker v-model="tempDateRange2" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" style="width: 240px;" @change="handleDateRangeChange2" />
          </div>
          <div class="search-item">
            <span class="search-label">业务员</span>
            <el-select v-model="searchForm.created_by" placeholder="请选择" clearable style="width: 120px;">
              <el-option label="业务员1" value="1" />
              <el-option label="业务员2" value="2" />
              <el-option label="业务员3" value="3" />
            </el-select>
          </div>
          <div class="search-item">
            <span class="search-label">商品</span>
            <el-select v-model="searchForm.goods_codes" placeholder="请选择商品" clearable multiple style="width: 200px;"
              filterable>
              <el-option v-for="goods in allGoodsList" :key="goods.goods_id" :label="goods.name" :value="goods.code" />
            </el-select>
          </div>
          <el-button type="primary" @click="searchGoods">查询</el-button>
        </div>
      </div>

      <!-- 显示方式切换 -->
      <div class="display-toggle">
        <el-radio-group v-model="displayMode">
          <el-radio-button label="byOrder" @click="changeDeplayByOrder">按单据显示</el-radio-button>
          <el-radio-button label="byGoods" @click="changeDeplayByGoods">按商品显示</el-radio-button>
        </el-radio-group>
      </div>

      <el-table :data="comparisonGoodsList" border style="width: 100%;height: 280px;" class="supplier-table"
        v-loading="comparisonGoodsLoading" @selection-change="handleComparisonSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="单据日期" prop="procurementOrder_date" width="160" />
        <el-table-column label="订单编号" prop="procurementOrder_code" min-width="180" />
        <!-- 按商品展示 -->
        <el-table-column v-if="displayMode == 'byGoods'" label="商品编号" prop="goods_code" width="120" />
        <el-table-column v-if="displayMode == 'byGoods'" label="商品名称" prop="goods_name" width="180" />
        <el-table-column v-if="displayMode == 'byGoods'" label="品牌" prop="goods_brand" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="单位" prop="goods_moreUint" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="仓库" prop="goods_store" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="数量" prop="procureDetails_num" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="可用库存" prop="store_userNum" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="单价" prop="goods_price" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="含税单价" prop="afterDiscount_price" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="折后单价" prop="discount_price" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="折后含税单价" prop="afterDiscount_taxPrice" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="采购金额" prop="totalAmount_includingTax" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="税额" prop="tax_amount" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="折扣额" prop="discount_amount" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="价税合计" prop="totalAmount_includingTax" width="160" />
        <el-table-column v-if="displayMode == 'byGoods'" label="税率" prop="tax" width="160" />
        <!-- 按商品展示 -->
        <!-- 按单据展示 -->
        <el-table-column v-if="displayMode == 'byOrder'" label="供应商" prop="supplier_name" min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="业务员" prop="created_by" min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="交货日期" prop="delivery_date" min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="数量" prop="procurementOrder_num " min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="采购金额" prop="procurement_amount" min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="税额" prop="tax_amount" min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="优惠后金额" prop="afterDiscount_amount" min-width="180" />
        <el-table-column v-if="displayMode == 'byOrder'" label="折扣额" prop="discount_amount" min-width="180" />
        <!-- 按单据展示 -->
        <el-table-column label="制单人" prop="created_by" width="160" />
      </el-table>
      <el-pagination style="float: left; margin-top: 16px;" background layout="prev, pager, next, jumper"
        :total="comparisonGoodsPageInfo.total" :page-size="comparisonGoodsPageInfo.pageSize"
        :current-page="comparisonGoodsPageInfo.pageNum" @current-change="changePage" />
      <div class="dialog-footer" style="text-align: right; margin-top: 20px;">
        <el-button @click="openComparisonGoodsDialogView = false">取消</el-button>
        <el-button type="primary" @click="confirmComparisonGoods"
          :disabled="selectedComparisonGoods.length === 0 && selectedComparisonGoodsByCode.length === 0">
          确定选择
        </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 仓库搜索列表弹出对话框 -->
  <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable :show-close="true">
    <!-- 调用仓库的搜索组件 -->
    <WareHouse ref="warehouseRef"
      :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
    <br /><br />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="warehouseVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmWarehouseSelection">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import SupplierDialog from '@/util/SupplierDialog.vue';
import WareHouse from '../basic/WareHouse.vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';

// import { it } from 'element-plus/es/locale';
// import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
// 判断是否为编辑模式
const isEdit = computed(() => route.query.isEdit === 'true')

onMounted(() => {
  if (isEdit.value) {
    loadEditData()
  }
  getAccountList()
})

//获取结算账号列表
const accountList = ref([])

const getAccountList = async () => {
  const res = await axios.get("/lxw/getAccountList")
  if (res.data.code == 5200) {
    accountList.value = res.data.accountList
    console.log("账户列表", accountList.value)
  } else {
    ElMessage.warning(res.data.msg)
  }
}
const handleAccountChange = () => {
  console.log('选中账户ID:', form.payment_account)
  const selectedAccount = accountList.value.find(item => item.account_id == form.payment_account)
  console.log('选中账户详情:', selectedAccount)
}

// 多单位实现
const getUnitList = async (row) => {
  // 如果已经有单位列表了，直接返回
  if (row.unitList && row.unitList.length > 0) {
    return;
  }

  // 添加加载状态
  row.unitLoading = true;
  try {
    const res = await axios.get('/lxw/getUnitsByGoodsId', {
      params: { goodsId: row.goods_id }
    });
    if (res.data.code === 5200) {
      console.log("unitsDetailList", res.data.unitsDetailList)
      row.unitList = (res.data.unitsDetailList || []).map(u => ({
        id: u.id,
        name: u.name || row.goods_moreUint,
        conversion: u.conversion || 1,
        unitsId: u.id // 修正这里的变量名
      }));
      if (res.data.unitsDetailList.name == null) {
        row.unit_num = 1
      }
      console.log("unitList", row.unitList)
      updateUnitNum(row)
    } else {
      ElMessage.warning('单位加载失败');
      row.unitList = [];
    }
  } catch (err) {
    console.error('加载单位出错:', err);
    ElMessage.error('单位加载异常');
    row.unitList = [];
  } finally {
    row.unitLoading = false;
  }
}



const updateUnitNum = (row) => {
  console.log("xxx", row)
  if (!row.goods_moreUint || !Array.isArray(row.unitList) || row.unitList.length === 0) {
    row.unit_num = 1;
    return;
  }

  // 找到当前选中的单位
  const selectedUnit = row.unitList.find(unit => unit.name === row.goods_moreUint);
  console.log("找到当前选中的单位", selectedUnit)

  if (!selectedUnit) {
    row.unit_num = 1;
    return;
  }

  // 获取采购数量（用户输入）
  const procureNum = parseFloat(row.procurementDetail_num) || 0;

  // 计算基本数量 = 采购数量 × 单位换算系数（conversion）
  const baseNum = procureNum * (parseFloat(selectedUnit.conversion) || 1);

  // 保留合理小数位（比如最多3位，或根据业务决定）
  row.unit_num = isNaN(baseNum) ? '' : baseNum;
};

const warehouseVisible = ref(false)
const warehouseRef = ref()
const currentEditingRow = ref(null)  // 当前正在编辑的行数据
const currentEditingIndex = ref(-1)  // 当前正在编辑的行索引

// 打开仓库选择对话框
const openWarehouseDialog = (row, index) => {
  currentEditingRow.value = row
  currentEditingIndex.value = index
  warehouseVisible.value = true

  // 如果有需要，可以在这里设置初始选中的仓库
  // 根据你的 WareHouse 组件的 API 来设置
}

// 确认仓库选择
const confirmWarehouseSelection = async () => {
  if (warehouseRef.value && warehouseRef.value.selectedArray && warehouseRef.value.selectedArray.length > 0) {
    // 获取选中的仓库（假设单选，取第一个）
    const selectedWarehouse = warehouseRef.value.selectedArray[0]

    // 更新当前行的仓库信息
    if (currentEditingRow.value) {
      currentEditingRow.value.goods_store = selectedWarehouse.name
      // 如果需要存储仓库编码
      currentEditingRow.value.warehouse_code = selectedWarehouse.code
      // 或者其他需要的字段
      // currentEditingRow.value.warehouse_id = selectedWarehouse.id
      //处理当前仓库的可用库存

      const params = {
        warehouse_name: currentEditingRow.value.goods_store,
        goods_id: currentEditingRow.value.goods_id
      }
      const res = await axios.get("/lxw/getStoreUseNum", { params })
      if (res.data.code == 5200) {
        const inventory = res.data.Inventory
        if (inventory?.totalNumber == null) {
          currentEditingRow.value.moreUnit_num = 0
        } else {
          currentEditingRow.value.moreUnit_num = inventory.totalNumber - inventory.lockedNumber
        }
      }
    }

    // 清空选择
    if (warehouseRef.value.clearSelected) {
      warehouseRef.value.clearSelected()
    }
  }

  // 关闭对话框
  warehouseVisible.value = false
  resetEditingState()
}

// 重置编辑状态
const resetEditingState = () => {
  currentEditingRow.value = null
  currentEditingIndex.value = -1
}

// 加载编辑数据
const loadEditData = async () => {
  try {
    // 从本地存储获取数据
    const procurement_id = route.query.procurement_id;
    if (!procurement_id) return;

    const res = await axios.get(`/lxw/selectProcurementById?procurement_id=${procurement_id}`);
    console.log("修改数据回显", res)
    if (res.data.code == 5200) {
      const data = res.data.procurement;

      // 填充主表单数据
      Object.assign(form, {
        ...data
      })

      // 为每个新商品加载单位列表

      // 填充供应商信息
      Object.assign(selectedSupplier, {
        SupplierName: data.supplier_name,
        SupplierCode: data.supplier_code,
        supplierAddress: data.supplier_shippingAddress || ''
      })
      // 为每个商品加载单位列表
      if (data.detailList && data.detailList.length > 0) {
        data.detailList.map(item => {
          console.log("item", item)
          getUnitList(item);
        });
      }

      ElMessage.success('已加载编辑数据')
    }
  } catch (error) {
    console.error('加载编辑数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 对话框引用
const supplierDialog = ref(null);
// 选择的供应商
const selectedSupplier = reactive({
  SupplierName: '',
  SupplierConcat: '',
  SupplierPhone: '',
  supplierAddress: '',
  totalDebt: 0
});
// 表单数据
const form = reactive({
  procurement_id: '',
  procurement_date: '',
  procurement_code: '',
  supplier_id: '',
  supplier_code: '',
  supplier_name: '',
  supplier_type: '购货',
  procurement_address: '',
  buyer: '',
  procurementRefund_code: '',
  procurementOrder_code: '',
  procurement_quantity: '',
  buy_amount: '',
  discount_amount: '',
  afterDiscount_amount: '',
  tax_amount: '',
  payment_account: '',
  pay_amount: '',
  pay_status: '0',
  refund_status: '0',
  matching_status: '0',
  checked_status: '0',
  created_by: sessionStorage.getItem("name"),
  craeted_id: '',
  created_date: new Date,
  procurement_amount: '',
  isRefund: 0,
  checked_by: '',
  procurement_remark: '',
  delivery_method: '',
  printf_num: '',
  isDelete: '',
  companyCode: 'CNY001',
  detailList: []
})

// 计算本次欠款
const remainingAmount = computed(() => {
  const procurementAmount = parseFloat(form.procurement_amount) || 0
  const payAmount = parseFloat(form.pay_amount) || 0

  // 欠款 = 采购费用 - 本次付款
  const remaining = procurementAmount - payAmount

  // 确保欠款不小于0
  return Math.max(remaining, 0).toFixed(2)
})
// 文件上传
const fileList = ref([])

const calculateDetailPrice = (row) => {
  updateUnitNum(row)
  console.log("是否是赠品", row.gift)
  if (row.gift) {
    row.afterDiscount_price = 0
    row.taxPrice = 0
    row.afterDiscount_taxPrice = 0
    row.discount = 0
    row.discount_price = 0
    row.discount_amount = 0
    row.amount = 0
    row.tax = 0
    row.tax_amount = 0
    row.totalAmount_includingTax = 0
  } else {
    console.log(row.goods_price)
    console.log(row.procurementDetail_num)
    if (row.goods_price == 0 || row.procurementDetail_num == 0) {
      row.afterDiscount_price = 0
      row.taxPrice = 0
      row.afterDiscount_taxPrice = 0
      row.discount = 0
      row.discount_price = 0
      row.discount_amount = 0
      row.amount = 0
      row.tax = 0
      row.tax_amount = 0
      row.totalAmount_includingTax = 0
    } else {
      row.discount_price = formatPrice(row.goods_price * (1 - (row.discount || 0) / 100))
      row.discount_amount = formatPrice((row.goods_price - row.discount_price) * row.unit_num)

      row.afterDiscount_taxPrice = formatPrice(row.discount_price * (1 + (row.tax || 0) / 100))
      row.totalAmount_includingTax = formatPrice(row.afterDiscount_taxPrice * row.unit_num)

      row.afterDiscount_price = formatPrice(row.goods_price * (1 + (row.tax || 0) / 100))
      row.tax_amount = formatPrice((row.afterDiscount_taxPrice - row.discount_price) * row.unit_num)

      row.amount = formatPrice(row.discount_price * row.unit_num)

    }
  }
  calculateTotalAmount()
  calculateTotalDiscountAmount()
  calculateTotal()
  calculateTotalTax()
  calculateBeforeDiscountAmount()
  calculateTotalNum()
}
const formatPrice = (num) => Math.round(num * 100) / 100
// 计算（实付金额）
const calculateTotalAmount = () => {
  const total = form.detailList.reduce((sum, item) => {
    return sum + (parseFloat(item.totalAmount_includingTax) || 0);
  }, 0);
  form.procurement_amount = total.toFixed(2);
};
//计算总折扣额
const calculateTotalDiscountAmount = () => {
  const total = form.detailList.reduce((sum, item) => {
    return sum + (parseFloat(item.discount_amount) || 0);
  }, 0);
  form.discount_amount = total.toFixed(2);
}
//计算折扣后金额（金额）
const calculateTotal = () => {
  const total1 = form.detailList.reduce((sum, item) => {
    return sum + (parseFloat(item.amount) || 0);
  }, 0);
  form.afterDiscount_amount = (total1).toFixed(2)
}
//计算总税额
const calculateTotalTax = () => {
  const total = form.detailList.reduce((sum, item) => {
    return sum + (parseFloat(item.tax_amount) || 0);
  }, 0);
  form.tax_amount = total.toFixed(2);
}
//计算订单总数量
const calculateTotalNum = () => {
  const total = form.detailList.reduce((sum, item) => {
    return sum + (parseFloat(item.procurementDetail_num) || 0);
  }, 0);
  form.procurement_quantity = Number(total.toFixed(0));
}

//计算购货费用
const calculateBeforeDiscountAmount = () => {
  const afterDiscount = parseFloat(form.afterDiscount_amount) || 0;
  const discount = parseFloat(form.discount_amount) || 0;
  const amount = afterDiscount + discount;
  form.buy_amount = amount.toFixed(2);
}
//选择添加的商品
const openGoodsDialogView = ref(false)

const openGoodsDialog = () => {
  openGoodsDialogView.value = true;
}

// 处理选中的商品
const handleGoodsConfirm = (selectedGoods) => {
  console.log('选中的商品:', selectedGoods)

  if (selectedGoods && selectedGoods.length > 0) {
    // 转换商品数据格式，适配采购订单表格
    const newItems = selectedGoods.map(goods => ({
      goods_id: goods.id,
      goods_code: goods.code,
      goods_name: goods.name,
      goods_specifiction: goods.specification,
      goods_brand: goods.brandName,
      goods_price: 0, // 初始价格为0，需要手动填写
      procurementDetail_num: 1,
      unitsId: goods.unit,
      unitType: goods.unitType,
      goods_moreUint: goods.unitName,
      goods_store: goods.warehouseName,
      moreUnit_num: goods.stock,
      goods_unit: goods.unitName,
      unit_num: 0,
      inspected_quantity: '',
      gift: false,
      afterDiscount_price: 0,
      taxPrice: 0,
      afterDiscount_taxPrice: 0,
      discount: 0,
      discount_price: 0,
      discount_amount: 0,
      amount: 0,
      tax: 0,
      tax_amount: 0,
      totalAmount_includingTax: 0,
      procurementDetail_remark: '',
      companyCode: 'CNY001',
    }))


    // 添加到采购订单物品列表
    form.detailList.push(...newItems);

    // 为每个新商品加载单位列表
    newItems.forEach(item => {
      getUnitList(item);
      updateUnitNum(item)
    });
    console.log('newItem', form.detailList.values)
    calculateTotalAmount();
    ElMessage.success(`成功添加 ${newItems.length} 个商品`);
  }
}

// 删除物品
const removeItem = (index) => {
  form.detailList.splice(index, 1);
  calculateTotalAmount();
  ElMessage.success('删除成功');
}

// 保存并且新增
const handleSubmit = async () => {
  if (isEdit.value) {
    await handleModify()
  } else {
    await handleAdd(true)
  }
}

// 保存
const handleSubmit2 = async () => {
  if (isEdit.value) {
    await handleModify()
  } else {
    await handleAdd(false)
  }
}
// 新增采购订单-手动添加
const handleAdd = async (isAddNew) => {
  // 验证供应商
  if (!selectedSupplier.SupplierName) {
    ElMessage.warning('请选择供应商');
    return;
  }

  // 验证物品信息
  if (form.detailList.length === 0) {
    ElMessage.warning('请至少添加一个采购物品');
    return;
  }

  try {
    await ElMessageBox.confirm('确定要提交采购订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const orderData = {
      procurement_code: form.procurement_code,
      procurement_date: formatDate(form.procurement_date),
      supplier_id: form.supplier_id,
      supplier_code: form.supplier_code,
      supplier_name: form.supplier_name,
      supplier_type: form.supplier_type,
      procurement_address: form.procurement_address,
      buyer: form.buyer,
      procurementRefund_code: form.procurementRefund_code,
      procurementOrder_code: form.procurementOrder_code,
      procurement_quantity: form.procurement_quantity,
      buy_amount: form.buy_amount,
      discount_amount: form.discount_amount,
      afterDiscount_amount: form.afterDiscount_amount,
      tax_amount: form.tax_amount,
      pay_amount: form.pay_amount,
      payment_account: form.payment_account,
      pay_status: form.pay_status,
      refund_status: form.refund_status,
      matching_status: form.matching_status,
      checked_status: form.checked_status,
      created_by: form.buyer,
      created_date: form.created_date,
      procurement_amount: form.procurement_amount,
      isRefund: form.isRefund,
      checked_by: form.checked_by,
      procurement_remark: form.procurement_remark,
      delivery_method: form.delivery_method,
      printf_num: form.printf_num,
      companyCode: form.companyCode,
      detailList: form.detailList
    };

    const res = await axios.post('/lxw/insertProcurement', orderData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    console.log(res)
    if (res.data.code == 5200) {
      ElMessage.success('订单提交成功！');
      if (isAddNew) {
        handleReset();
      }
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    console.log('用户取消提交');
  }
}

//新增采购订单-选择源单
const openComparisonGoodsDialogView = ref(false)

const comparisonGoodsList = ref([])

const comparisonGoodsLoading = ref(false)
// 添加必要的响应式数据
const goodsSearch = ref('')
const selectedComparisonGoods = ref([])
const selectedComparisonGoodsByCode = ref([])

// 处理表格选择变化
const handleComparisonSelectionChange = (selection) => {
  if (displayMode.value == 'byGoods') {
    selectedComparisonGoods.value = selection
  }
  else {
    selectedComparisonGoodsByCode.value = selection
  }

}

//商品列表查询
const allGoodsList = ref([])

const getAllGoodsList = async () => {
  const res = await axios.post('/lxw/allGoods')
  if (res.data.code == 5200) {
    console.log("全部商品列表", res)
    allGoodsList.value = res.data.goodsList
    ElMessage.warning(res.data.msg)
  }
}
// 搜索商品
const searchGoods = () => {
  if (displayMode.value == 'byGoods') {
    getComparisonGoods()
  }
  else {
    getComparisonGoodsByCode()
  }
}

//比价单商品选择分页信息
const comparisonGoodsPageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const initComparisonGoodsPageInfo = () => {
  comparisonGoodsPageInfo.pageNum = 1,
    comparisonGoodsPageInfo.pageSize = 10,
    comparisonGoodsPageInfo.total = 0
}
//分页变化
const changePage = (page) => {
  comparisonGoodsPageInfo.pageNum = page;
  getComparisonGoods()
};
// 搜索表单数据
const searchForm = reactive({
  order_startDate: '',
  order_endDate: '',
  procurementOrder_code: '',
  delivery_startDate: '',
  delivery_endDate: '',
  goods_store: '',
  created_by: '',
  goods_codes: []
})

// 显示模式
const displayMode = ref('byGoods')

//更换展示方式
const changeDeplayByGoods = () => {
  displayMode.value = 'byGoods'
  initComparisonGoodsPageInfo()
  getComparisonGoods()
}

const changeDeplayByOrder = () => {
  displayMode.value = 'byOrder'
  initComparisonGoodsPageInfo()
  getComparisonGoodsByCode()
}

// 临时存储日期范围
const tempDateRange = ref([])

// 日期范围变化处理
const handleDateRangeChange = (dateRange) => {
  if (dateRange && dateRange.length === 2) {
    searchForm.order_startDate = dateRange[0]
    searchForm.order_endDate = dateRange[1]
  } else {
    searchForm.order_startDate = ''
    searchForm.order_endDate = ''
  }
}

// 临时存储日期范围
const tempDateRange2 = ref([])

// 日期范围变化处理
const handleDateRangeChange2 = (dateRange) => {
  if (dateRange && dateRange.length === 2) {
    searchForm.delivery_startDate = dateRange[0]
    searchForm.delivery_endDate = dateRange[1]
  } else {
    searchForm.delivery_startDate = ''
    searchForm.delivery_endDate = ''
  }
}
// 获取源商品数据 - 修正参数传递
const getComparisonGoods = async () => {
  comparisonGoodsLoading.value = true
  try {
    const res = await axios.get('/lxw/selectByCondition', {
      params: {
        pageNum: comparisonGoodsPageInfo.pageNum,
        pageSize: comparisonGoodsPageInfo.pageSize,
        supplier_code: form.supplier_code,
        ...searchForm,
        // 单独处理数组参数
        goods_codes: searchForm.goods_codes.join(',') // 转换为逗号分隔的字符串
      }
    })
    console.log("该供应商下的比价商品信息", res)
    if (res.data.code == 5200) {
      comparisonGoodsList.value = res.data.procurementOrder.list || []
      comparisonGoodsPageInfo.pageNum = res.data.procurementOrder.pageNum
      comparisonGoodsPageInfo.pageSize = res.data.procurementOrder.pageSize
      comparisonGoodsPageInfo.total = res.data.procurementOrder.total
    } else {
      ElMessage.error(res.data.msg)
      comparisonGoodsList.value = []
    }
  } catch (error) {
    console.error('获取比价商品失败:', error)
    ElMessage.error('获取商品信息失败')
    comparisonGoodsList.value = []
  } finally {
    comparisonGoodsLoading.value = false
  }
}

// 通过单据获取源商品数据 - 修正参数传递
const getComparisonGoodsByCode = async () => {
  comparisonGoodsLoading.value = true
  try {
    const res = await axios.get('/lxw/selectAllOrder', {
      params: {
        pageNum: comparisonGoodsPageInfo.pageNum,
        pageSize: comparisonGoodsPageInfo.pageSize,
        companyCode: 'CNY001',
        supplier_code: form.supplier_code,
        isProcurementChoose: 1,
        ...searchForm,
        // 单独处理数组参数
        goods_codes: searchForm.goods_codes.join(',') // 转换为逗号分隔的字符串
      }
    })
    console.log("该供应商下的比价商品信息", res)
    if (res.data.code == 5200) {
      // 确保返回的数据包含明细列表
      const orderList = res.data.orderPageInfo.list || []

      // 如果需要，可以在这里为每个订单添加获取明细的逻辑
      // 或者确保后端返回的数据已经包含了 detailList

      comparisonGoodsList.value = orderList
      comparisonGoodsPageInfo.pageNum = res.data.orderPageInfo.pageNum
      comparisonGoodsPageInfo.pageSize = res.data.orderPageInfo.pageSize
      comparisonGoodsPageInfo.total = res.data.orderPageInfo.total
    } else {
      ElMessage.error(res.data.msg)
      comparisonGoodsList.value = []
    }
  } catch (error) {
    console.error('获取比价商品失败:', error)
    ElMessage.error('获取商品信息失败')
    comparisonGoodsList.value = []
  } finally {
    comparisonGoodsLoading.value = false
  }
}

// 确认选择比价商品
const confirmComparisonGoods = async () => {
  if (displayMode.value == "byGoods") {
    if (selectedComparisonGoods.value.length === 0) {
      ElMessage.warning('请至少选择一件商品')
      return
    }

    // 验证商品是否可以进入采购单明细
    const validGoods = await validateGoodsForProcurement(selectedComparisonGoods.value);
    if (validGoods.length === 0) {
      ElMessage.warning('选中的商品均不可添加，请检查商品状态');
      return;
    }

    // 获取源单编号（去重）
    const sourceOrderCodes = [...new Set(validGoods.map(goods => goods.procurementOrder_code))];

    // 更新源单编号
    updateSourceOrderCodes(sourceOrderCodes);

    console.log("validGoods", validGoods)
    // 转换比价商品数据为采购订单明细格式
    const newItems = validGoods.map(goods => ({
      goods_id: goods.goods_id,
      goods_code: goods.goods_code,
      goods_name: goods.goods_name,
      goods_specifiction: goods.goods_specifiction,
      goods_brand: goods.goods_brand,
      goods_unit: goods.goods_unit,
      goods_price: goods.goods_price,
      procurementDetail_num: goods.procureDetails_num,
      goods_moreUint: goods.goods_moreUint,
      goods_store: goods.goods_store,
      moreUnit_num: goods.store_userNum,
      unit_num: goods.unit_num,
      gift: goods.gift,
      afterDiscount_price: goods.afterDiscount_price,
      taxPrice: goods.taxPrice,
      afterDiscount_taxPrice: goods.afterDiscount_taxPrice,
      discount: goods.discount,
      discount_price: goods.discount_price,
      discount_amount: goods.discount_amount,
      amount: goods.amount,
      tax: goods.tax,
      tax_amount: goods.tax_amount,
      totalAmount_includingTax: goods.totalAmount_includingTax,
      companyCode: goods.companyCode,
      // 保留源单信息
      procurementDetailOrder_code: goods.procurementOrder_code
    }))

    // 添加到采购订单物品列表
    form.detailList.push(...newItems)

    // 重新计算所有商品的价格和多单位
    console.log("选择源单的商品明细", form.detailList)
    form.detailList.forEach(item => {
      getUnitList(item)
      updateUnitNum(item)
      calculateDetailPrice(item)
    })

    // 更新总计
    calculateTotalAmount()
    calculateTotalDiscountAmount()
    calculateTotal()
    calculateTotalTax()
    calculateBeforeDiscountAmount()
    calculateTotalNum()

    const skippedCount = selectedComparisonGoods.value.length - validGoods.length;
    let message = `成功添加 ${newItems.length} 个商品`;
    if (skippedCount > 0) {
      message += `，跳过 ${skippedCount} 个不可添加的商品`;
    }

    ElMessage.success(message)
    openComparisonGoodsDialogView.value = false
    selectedComparisonGoods.value = [] // 清空选择
  }
  else {
    // 按单据显示模式
    if (selectedComparisonGoodsByCode.value.length === 0) {
      ElMessage.warning('请至少选择一个单据')
      return
    }

    // 验证单据下所有商品，只添加合格的
    const { validItems, orderStats } = await validateAndFilterOrderGoods(selectedComparisonGoodsByCode.value);

    if (validItems.length === 0) {
      ElMessage.warning('选中的单据中没有可添加的商品明细');
      return;
    }

    // 获取源单编号（只包含有合格商品的单据）
    const sourceOrderCodes = [...new Set(validItems.map(item => item.procurementDetailOrder_code))];

    // 更新源单编号
    updateSourceOrderCodes(sourceOrderCodes);

    // 转换商品数据为采购订单明细格式
    const allNewItems = validItems.map(item => ({
      goods_id: item.goods_id,
      goods_code: item.goods_code,
      goods_name: item.goods_name,
      goods_specifiction: item.goods_specifiction,
      goods_brand: item.goods_brand,
      goods_unit: item.goods_unit,
      goods_price: item.goods_price || 0,
      procurementDetail_num: item.procureDetails_num || 1,
      goods_moreUint: item.goods_moreUint,
      goods_store: item.goods_store || '',
      moreUnit_num: item.store_userNum || 0,
      unit_num: item.unit_num || item.procureDetails_num,
      gift: item.gift || false,
      afterDiscount_price: item.afterDiscount_price || 0,
      taxPrice: item.taxPrice || 0,
      afterDiscount_taxPrice: item.afterDiscount_taxPrice || 0,
      discount: item.discount || 0,
      discount_price: item.discount_price || 0,
      discount_amount: item.discount_amount || 0,
      amount: item.amount || 0,
      tax: item.tax || 0,
      tax_amount: item.tax_amount || 0,
      totalAmount_includingTax: item.totalAmount_includingTax || 0,
      procurementDetail_remark: item.goods_remark || '',
      companyCode: item.companyCode || 'CNY001',
      // 保留源单信息
      procurementDetailOrder_code: item.procurementDetailOrder_code
    }))

    // 添加到采购订单物品列表
    form.detailList.push(...allNewItems)

    console.log("选择源单的商品明细", form.detailList)
    // 重新计算所有商品的价格
    form.detailList.forEach(item => {
      getUnitList(item)
      updateUnitNum(item)
      calculateDetailPrice(item)
    })

    // 更新总计
    calculateTotalAmount()
    calculateTotalDiscountAmount()
    calculateTotal()
    calculateTotalTax()
    calculateBeforeDiscountAmount()
    calculateTotalNum()

    // 生成详细的结果消息
    const message = generateOrderSelectionMessage(orderStats, validItems.length, sourceOrderCodes.length);
    ElMessage.success(message)

    openComparisonGoodsDialogView.value = false
    selectedComparisonGoodsByCode.value = [] // 清空选择
    displayMode.value = "byGoods"
  }
}

// 验证并过滤单据商品 - 核心逻辑
const validateAndFilterOrderGoods = async (orderList) => {
  const validItems = [];
  const orderStats = []; // 记录每个单据的统计信息

  for (const order of orderList) {
    let validCount = 0;
    let totalCount = 0;

    if (order.detailList && order.detailList.length > 0) {
      totalCount = order.detailList.length;

      for (const detail of order.detailList) {
        try {
          const procurementOrderDetail = {
            procurementOrder_code: order.procurementOrder_code,
            goods_code: detail.goods_code,
            goods_name: detail.goods_name,
            procureDetails_num: detail.procureDetails_num,
            procurementDetailOrder_code: order.procurementOrder_code
          };

          const res = await axios.post('/lxw/checkOrderCanProcurement', procurementOrderDetail);

          if (res.data.code === '5200') {
            validItems.push({
              ...detail,
              procurementDetailOrder_code: order.procurementOrder_code
            });
            validCount++;
          } else {
            console.warn(`单据 ${order.procurementOrder_code} 的商品 ${detail.goods_name} 不可添加:`, res.data.msg);
          }
        } catch (error) {
          console.error(`验证单据 ${order.procurementOrder_code} 的商品 ${detail.goods_name} 失败:`, error);
          // 验证失败时，默认不允许添加
        }
      }
    }

    // 记录每个单据的统计信息
    orderStats.push({
      orderCode: order.procurementOrder_code,
      totalCount,
      validCount,
      skippedCount: totalCount - validCount
    });
  }

  return { validItems, orderStats };
}

// 生成订单选择结果消息
const generateOrderSelectionMessage = (orderStats, totalValidItems, totalValidOrders) => {
  // const validOrders = orderStats.filter(stat => stat.validCount > 0);
  const emptyOrders = orderStats.filter(stat => stat.validCount === 0);

  let message = `成功添加 ${totalValidItems} 个商品（来自 ${totalValidOrders} 个单据）`;

  // 添加详细信息
  if (emptyOrders.length > 0) {
    message += `，${emptyOrders.length} 个单据无合格商品`;
  }

  // 添加跳过商品数量信息
  const totalSkipped = orderStats.reduce((sum, stat) => sum + stat.skippedCount, 0);
  if (totalSkipped > 0) {
    message += `，跳过 ${totalSkipped} 个不可添加的商品`;
  }

  return message;
}

// 验证商品是否可以进入采购单明细（保持不变）
const validateGoodsForProcurement = async (goodsList) => {
  const validGoods = [];

  for (const goods of goodsList) {
    try {
      const procurementOrderDetail = {
        procurementOrder_code: goods.procurementOrder_code,
        goods_code: goods.goods_code,
        goods_name: goods.goods_name,
        procureDetails_num: goods.procureDetails_num
      };

      const res = await axios.post('/lxw/checkOrderCanProcurement', procurementOrderDetail);

      if (res.data.code === '5200') {
        validGoods.push(goods);
      } else {
        console.warn(`商品 ${goods.goods_name} 不可添加:`, res.data.msg);
      }
    } catch (error) {
      console.error(`验证商品 ${goods.goods_name} 失败:`, error);
    }
  }

  return validGoods;
}

// 更新源单编号的方法
const updateSourceOrderCodes = (newOrderCodes) => {
  const filteredCodes = newOrderCodes.filter(code => code && code.trim() !== '');
  form.procurementOrder_code = filteredCodes.join(',');

  console.log('更新后的源单编号:', form.procurementOrder_code);
}
// 修改 chooseOrder 方法，添加验证
const chooseOrder = () => {
  if (!form.supplier_name) {
    ElMessage.warning("请先选择供应商")
    return
  }
  openComparisonGoodsDialogView.value = true
  goodsSearch.value = '' // 清空搜索条件
  selectedComparisonGoods.value = [] // 清空选择
  getComparisonGoods()
  getAllGoodsList()
}
// 修改询价单
const handleModify = async () => {
  // 验证供应商
  if (!selectedSupplier.SupplierName) {
    ElMessage.warning('请选择供应商');
    return;
  }

  // 验证物品信息
  if (form.detailList.length === 0) {
    ElMessage.warning('请至少添加一个采购物品');
    return;
  }

  try {
    await ElMessageBox.confirm('确定要修改采购订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const orderData = {
      ...form
    };

    const res = await axios.post('/lxw/updateProcurement', orderData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    console.log(res)
    if (res.data.code == 5200) {
      ElMessage.success('订单修改成功！');
      router.back();
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    console.log('用户取消修改');
  }
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 重置表单
const handleReset = () => {
  Object.assign(selectedSupplier, {
    SupplierName: '',
    SupplierConcat: '',
    SupplierPhone: '',
    supplierAddress: '',
    totalDebt: 0
  });
  Object.assign(form, {
    procurementOrder_id: '',
    procurementOrder_code: '',
    procurement_code: '',
    salesSlip_code: '',
    comparison_code: '',
    procurement_amount: '',
    discount_amount: '',
    afterDiscount_amount: '',
    tax_amount: '',
    procurementOrder_num: '',
    procurementOrder_status: 1,
    created_by: '',
    delivery_method: '',
    companyCode: 'CNY001',
    procurementOrder_date: new Date(),
    delivery_date: '',
    supplier_code: '',
    supplier_name: '',
    procurementOrder_remark: '',
    isDelete: 0,
    supplier_shippingAddress: selectedSupplier.supplierAddress || '',
    detailList: []
  });
  fileList.value = [];
  ElMessage.info('表单已重置');
}


// 处理供应商选择确认
const handleSupplierConfirm = (supplier) => {
  if (supplier) {
    Object.assign(selectedSupplier, supplier);
    ElMessage.success(`已选择供应商：${supplier.SupplierName || '空选'}`);
  } else {
    // 如果 supplier 是 null 或 undefined，清空 selectedSupplier
    Object.keys(selectedSupplier).forEach(key => {
      selectedSupplier[key] = '';
    });
    ElMessage.success('已选择空选');
  }
  form.supplier_id = supplier?.SupplierId || ''
  form.supplier_code = supplier?.SupplierCode || ''
  form.supplier_name = supplier?.SupplierName || ''
  form.procurement_address = supplier?.supplierAddress || ''
};
// 合计行方法
const getSummary = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(val => !isNaN(val))) {
      sums[index] = ''
      return
    }
    const total = values.reduce((prev, curr) => prev + curr, 0)
    sums[index] = total.toFixed(2)
  })
  return sums
}
</script>

<style scoped>
.purchase-apply-container {
  height: 100%;
}

.form-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.order-number {
  font-size: 14px;
  color: #606266;
}

.fixed-height-dialog {
  max-height: 80vh;
}

:deep(.fixed-height-dialog .el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}

/* 供应商头部信息 */
.supplier-header {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fafafa;
}

.supplier-info-row,
.supplier-detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.supplier-detail-row {
  margin-bottom: 0;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.label.warning {
  color: #e6a23c;
}

.value {
  font-size: 14px;
  color: #303133;
}

.value.warning {
  color: #e6a23c;
  font-weight: bold;
}

/* 表单内容区域 - 可滚动 */
.form-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
  max-height: calc(100vh - 300px);
}

/* 固定底部操作按钮 */
.form-footer {
  border-top: 1px solid #e8e8e8;
  padding: 16px 20px;
  background: #fff;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.form-actions {
  text-align: center;
}

/* 采购明细区域 */
.form-section {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.operator-info {
  font-size: 14px;
  color: #606266;
}

.item-count {
  margin-left: auto;
  font-size: 14px;
  color: #606266;
  margin-left: 10px;
}

.items-table {
  margin-bottom: 16px;
}

/* 总计区域 */
.total-summary {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.summary-row {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 40px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.summary-value {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.summary-value.total-amount {
  font-size: 18px;
  color: #f56c6c;
}

/* 优化表格样式 */
:deep(.items-table .el-table__empty-block) {
  min-height: 100px;
}

:deep(.items-table .el-table__empty-text) {
  color: #909399;
  font-size: 14px;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}

/* 源单选择对话框样式 */
.supplier-dialog-content {
  padding: 0 20px;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

/* 表格样式优化 */
:deep(.supplier-table .el-table__header-wrapper) {
  background-color: #f5f7fa;
}

:deep(.supplier-table .el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 搜索区域样式 */
.search-area {
  margin-bottom: 20px;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fafafa;
}

.search-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-row:last-child {
  margin-bottom: 0;
}

.search-item {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.search-label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
  min-width: 70px;
  text-align: right;
  white-space: nowrap;
}

/* 显示方式切换 */
.display-toggle {
  margin: 16px 0;
  text-align: center;
}

/* 已选信息 */
.selected-info {
  float: left;
  margin-top: 16px;
  font-size: 14px;
  color: #606266;
  padding: 8px 0;
}

/* 确保搜索区域响应式 */
@media (max-width: 1200px) {
  .search-row {
    gap: 12px;
  }

  .search-item {
    margin-bottom: 8px;
  }
}
</style>